package com.jackeys.piaems.intrusionDetection;

import com.jackeys.piaems.dao.ImageDao;
import com.jackeys.piaems.controller.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: Handler
 * @Description:
 * @Author: Jackeys
 * @Date: 2021-06-28 17:33
 * @Version: 1.0
 */
@Slf4j
public class Handler extends Thread {

    private ImageDao imageDao;
    Socket s;
    int id;

    public Handler(Socket s, int id, ImageDao imageDao) {
        this.s = s;
        this.id = id;
        this.imageDao=imageDao;
    }

    @Override
    public void run() {
        log.debug("处理客户端请求");
        FileOutputStream fos = null;
        InputStream is = null;
        try {
            is = s.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String filename = System.currentTimeMillis() + ".jpg";
            String filepath = ResourceUtils.getURL("classpath:").getPath() + "resources/files/" + "/image/";
            ;
            File dirFile = new File(filepath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            System.out.println("read line " + id + " :" + filename);
            File file = new File(filepath + filename);
            int len = 0;
            int BUFSIZE = 1 * 1024;
            byte[] bytes = new byte[BUFSIZE];
            fos = new FileOutputStream(file);
            while ((len = is.read(bytes, 0, bytes.length)) != -1) {
                fos.write(bytes, 0, len);
                fos.flush();
            }
            imageDao.insertImage("http://localhost:8085/files/image/"+filename, new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()));
            WebSocketServer.broadCastInfo("实时刷新");
            log.debug("服务器处理请求成功");
            log.debug("=====================================================================");
            FileInputStream fs = new FileInputStream(filepath + filename);
        } catch (Exception e) {
            log.debug("服务器处理请求失败");
            log.debug("=====================================================================");
            e.printStackTrace();
        } finally {
            // 服务端就不要手贱 关了socket否则Python 会出现错误Errno 10054让客户端关掉就行啦
            try {
                System.out.println("close");
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
